package com.atguigu.web;

import com.atguigu.pojo.Book;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BookServlet extends BaseServlet{
    private BookService bookService = new BookServiceImpl();


    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //把添加的图书封装成一个图书对象。
        Book book = WebUtils.copyParamToBean(req.getParameterMap(),new Book());
        //保存图书到数据库
        bookService.addBook(book);
        //跳转到图书列表页面
        //调用list方法是要再一次刷新图书信息。

        //但是如果用请求转发的话，会有bug，如果用户按下功能键F5，则浏览器会发起记录中最后一次请求，造成表单重复提交。
        req.getRequestDispatcher("/manager/bookservlet?action=list").forward(req,resp);

    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、通过bookService查询全部图书
        List<Book> books = bookService.queryBooks();

        //2、设置域对象
        req.setAttribute("books",books);

        //3、请求转发到/pages/manager/book_manager.jsp页面
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }
}
